package com.xinxing.city.recovery.net;

import android.content.Context;
import android.util.Log;

import androidx.fragment.app.FragmentManager;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.xinxing.city.recovery.Constant;
import com.xinxing.city.recovery.RecoveryApplication;
import com.xinxing.city.recovery.utils.MyDialog;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpRequest {

    String mappurl = "https://apis.map.qq.com";
    private OkHttpClient client;
    private String token;
    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json");
    private FragmentManager frM;
    private JsonObject resData = null;
    public JsonObject getResData() {
        return resData;
    }
    public OkHttpRequest(Context content, FragmentManager fragmentManager) {
        client = new OkHttpClient();
        frM = fragmentManager;


        token =  RecoveryApplication.getInstance().getToken();

    }

    public void sendGetRequest(String url, Callback callback) {

        try {
            client = client.newBuilder().connectTimeout(60, TimeUnit.SECONDS).addInterceptor(new CustomInterceptor()).build();

            Request request = new Request.Builder()
                    .url(Constant.BaseUrl +url)
                    .addHeader("Auth-Token", token)
                    .build();

            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            MyDialog mydialog = MyDialog.newInstance("sendGetRequest",e.getMessage(),"","");
            mydialog.show(frM, "MyDialog");
        }


    }


    public void sendPostRequest(String url,String jsonBody,Callback callback) {

        try {
            client = client.newBuilder().addInterceptor(new CustomInterceptor()).build();

            RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonBody);
            Request request = new Request.Builder()
                    .url(Constant.BaseUrl+url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Auth-Token", token)
                    .build();

            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            MyDialog mydialog = MyDialog.newInstance("sendPostRequest",e.getMessage(),"","");
            mydialog.show(frM, "MyDialog");
        }

    }

    public void sendPostRequestN(String url,String jsonBody,String toke,Callback callback) {

        try {
            client = client.newBuilder().addInterceptor(new CustomInterceptorN()).build();

            RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, jsonBody);
            Request request = new Request.Builder()
                    .url(Constant.BaseUrl+url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Auth-Token", (toke != null && !toke.equals(""))?toke:token)
                    .build();

            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            /* MyDialog mydialog = MyDialog.newInstance("sendPostRequest",e.getMessage(),"","");
            mydialog.show(frM, "MyDialog");*/
        }

    }

    public void sendFileRequest(String url,File file, Callback callback) {

        try {

            client = client.newBuilder().addInterceptor(new CustomInterceptor()).build();
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("filename", file.getName(), requestBody)
                    .addFormDataPart("tt", "nm")
                    .addFormDataPart("pub", "true");


            Request request = new Request.Builder()
                    .url(Constant.BaseUrl+url)
                    .addHeader("Auth-Token", token)
                    .post(builder.build())
                    .build();

            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            MyDialog mydialog = MyDialog.newInstance("sendGetRequest",e.getMessage(),"","");
            mydialog.show(frM, "MyDialog");
        }


    }

    public void sendFileRequestN(String url,File file,String toke, Callback callback) {

        try {

            client = client.newBuilder().connectTimeout(60, TimeUnit.SECONDS).addInterceptor(new CustomInterceptorN()).build();
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("filename", file.getName(), requestBody)
                    .addFormDataPart("tt", "nm")
                    .addFormDataPart("pub", "true");


            Request request = new Request.Builder()
                    .url(Constant.BaseUrl+url)
                    .addHeader("Auth-Token",  (toke != null && !toke.equals(""))?toke:token)
                    .post(builder.build())
                    .build();

            client.newCall(request).enqueue(callback);
        } catch (Exception e) {
            Log.e("12345",e.getMessage());
        }


    }

    public void mapSendGetRequest(String url, Callback callback) {
        client = client.newBuilder().addInterceptor(new CustomInterceptorMap()).build();
        Log.e("url","url: "+mappurl+url);
        Request request = new Request.Builder()
                .url(mappurl+url)
                .build();

        client.newCall(request).enqueue(callback);
    }

    private class CustomInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            MyDialog mydialog;
            // 在发送请求前进行自定义操作
            Gson gson = new Gson();
            Response response = chain.proceed(originalRequest);
            String responseBody =  response.body().string();
            if (responseBody == null || responseBody.equals("")) {
                /*mydialog = MyDialog.newInstance("提示","返回为空或null","","");
                mydialog.show(frM, "MyDialog");*/
                resData = null;
            } else {
                Log.e("接口返回",responseBody);
                JsonElement jsonElement = gson.fromJson(responseBody, JsonElement.class);
                JsonObject resData2 = jsonElement.getAsJsonObject();

                if (response.isSuccessful()) {
                    if (response.code() != 200) {
                        mydialog = MyDialog.newInstance("提示","请求网略错误，或接口错误","","");
                        mydialog.show(frM, "MyDialog");
                        resData = null;
                    } else {

                        if (resData2.get("code").getAsInt() != 0) {
                            mydialog = MyDialog.newInstance("提示",resData2.get("message").getAsString(),"","");
                            mydialog.show(frM, "MyDialog");
                            resData = null;
                        } else {
                            resData = resData2;
                        }
                    }
                } else {
                    mydialog = MyDialog.newInstance("提示",resData2.get("message").toString(),"","");
                    mydialog.show(frM, "MyDialog");
                    resData = null;
                }
            }


            return response;
        }
    }

    private class CustomInterceptorN implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            MyDialog mydialog;
            // 在发送请求前进行自定义操作
            Gson gson = new Gson();
            Response response = chain.proceed(originalRequest);
            String responseBody =  response.body().string();
            if (responseBody == null || responseBody.equals("")) {
                resData = null;
            } else {
                Log.e("接口返回",responseBody);
                JsonElement jsonElement = gson.fromJson(responseBody, JsonElement.class);
                JsonObject resData2 = jsonElement.getAsJsonObject();

                if (response.isSuccessful()) {
                    if (response.code() != 200) {
                        resData = null;
                    } else {

                        if (resData2.get("code").getAsInt() != 0) {
                            resData = null;
                        } else {
                            resData = resData2;
                        }
                    }
                } else {
                    resData = null;
                }
            }


            return response;
        }
    }

    /**
     * 地图响应拦截器
     */
    private class CustomInterceptorMap implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            // 在发送请求前进行自定义操作
            Response response = chain.proceed(originalRequest);
            Gson gson = new Gson();

            if (response.isSuccessful()) {
                if (response.code() != 200) {
                    MyDialog mydialog = MyDialog.newInstance("提示","请求网略错误，或接口错误","","");
                    mydialog.show(frM, "MyDialog");
                    resData = null;
                }

                String responseBody =  response.body().string();
                JsonElement jsonElement = gson.fromJson(responseBody, JsonElement.class);
                JsonObject resData2 = jsonElement.getAsJsonObject();

                if (resData2.get("status").getAsInt() != 0) {
                    MyDialog mydialog = MyDialog.newInstance("提示",resData2.get("message").getAsString(),"","");
                    mydialog.show(frM, "MyDialog");
                    resData = null;
                } else {
                    resData = resData2;
                }
            } else {
                MyDialog mydialog = MyDialog.newInstance("提示","接口请求失败","","");
                mydialog.show(frM, "MyDialog");
                resData = null;
            }

            return response;
        }
    }

}
